
import scala.collection.mutable
import scala.io.Source
import scala.xml._

/**
 * Cet objet permet de télécharger une file RSS, d'extraire automatiquement les tags
 * et de construire une table de hachage
 */


class RssReader(url:String) {
	
  
  /**
   * Les items 
   */
  private val LABEL_ITEM        = "item"
  private val LABEL_TITLE       = "title"
  private val LABEL_LINK        = "link"
  private val LABEL_PUBDATE     = "pubDate"
  private val LABEL_CREATOR     = "creator"
  private val LABEL_DESCRIPTION = "description"
  private val LABEL_CATEGORIE   = "category"
  private val LABEL_IMAGE_URL   = "enclosure"

  
  /**
   * Table de hachage qui stocke la liste des items  
   */
  private var entries:mutable.ListBuffer[default.Entry] =new mutable.ListBuffer[default.Entry]
  
  
  /**
   * Le flux rss à parser
   */
  private var source:scala.io.Source=null
  
  /**
   * Fonction qui télécharge le flux rss
   */
  private def download()={
	 source=Source.fromURL((new java.net.URL(url))) 
  }
  
  /**
   * Construit les items à partir du flux rss
   */
  private def buildItems()={
    val rss=XML.load(url)
    val channel = rss.child.find(n => n.label == "channel")
    println(channel.get.child.length)
    buildElements(channel.get)
  }
  
  /**
   *Build elements 
   */
  private def buildElements(e:xml.Node):Unit={
    
      e.child.foreach(d => {
	      var entry = new default.Entry
	      
	      d.child.foreach(c=> {
	    	  c.label match{
	    	    case LABEL_CATEGORIE   => entry.Category    = c.text 
	    	    case LABEL_CREATOR     => entry.Creator     = c.text
	    	    case LABEL_DESCRIPTION => entry.Description = c.text
	    	    case LABEL_IMAGE_URL   => entry.Enclosure   = c.attribute("url").mkString
	    	    case LABEL_LINK        => entry.Link        = c.text
	    	    case LABEL_PUBDATE     => entry.PubDate     = c.text
	    	    case LABEL_TITLE       => entry.Title       = c.text
	    	    case _                 =>
	    	  }
	    	  entries+=entry
	        })
      })
    }
  
  
  
  /**
   * retourne les items
   */
  def getFeeds()={
    if (entries.length==0){
      buildItems()
    }
    entries
  }
}